package features.advance.jdk.dynamicproxy.jdk;

import java.lang.invoke.*;

import static java.lang.invoke.MethodHandles.lookup;

/**
 * @author LIN
 * @date 2021-12-29 15:14
 *
 *  invokedynamic指令。这条新增加的指令是JDK 7实现“动态类型语言”（Dynamically Typed Language）支持而进行的改进之一，也是为JDK 8可以顺利实现Lambda表达式做技术准备。
 *
 */
public class InvokeDynamicDemo {

    public static void main(String[]args)throws Throwable{
        INDY_BootstrapMethod().invokeExact("world");
    }
    public static void testMethod(String s){
        System.out.println("hello "+s);
    }
    public static CallSite BootstrapMethod(MethodHandles.Lookup lookup, String name, MethodType mt)throws Throwable{
        return new ConstantCallSite(lookup.findStatic(InvokeDynamicDemo.class,name,mt));
    }
    private static MethodType MT_BootstrapMethod(){
        return MethodType.fromMethodDescriptorString("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"
                ,null);
    }
    private static MethodHandle MH_BootstrapMethod()throws Throwable{
        return lookup().findStatic(InvokeDynamicDemo.class,"BootstrapMethod",MT_BootstrapMethod());
    }
    private static MethodHandle INDY_BootstrapMethod()throws Throwable{
        CallSite cs=(CallSite)MH_BootstrapMethod().invokeWithArguments(lookup(),"testMethod",MethodType.fromMethodDescriptorString("(Ljava/lang/String;)V",null));
        return cs.dynamicInvoker();
    }

}
